"use client";
import { Button } from "@/components/ui/button";
import { useQuery } from "@tanstack/react-query";
import { useEffect, useState } from "react";
import { ColDef } from "ag-grid-community";
import { DatePickerWithRange } from "@/components/date-picker";
import { DateRange } from "react-day-picker";
import { subDays } from "date-fns";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import DataGrid from "@/components/data-grid";
import {
  EnTaskStatus,
  type Task,
  RowActionsHandler,
  EnRowAction,
} from "../../types";
import { ChartsPage } from "./charts";
const headers = { "Content-Type": "application/json" };

const GoodsPage = () => {
  const [date, setDate] = useState<DateRange | undefined>({
    from: subDays(new Date(), 30),
    to: new Date(),
  });

  const [timeFrom, setTimeFrom] = useState(date?.from?.toISOString());
  const [timeTo, setTimeTo] = useState(date?.to?.toISOString());
  const [rowData, setRowData] = useState([]);
  const [message, setMessage] = useState("");
  const taskQuery = useQuery({
    queryKey: ["goods", timeFrom, timeTo],
    queryFn: () =>
      fetch(`/api/goods/timingnation?from=${timeFrom}&to=${timeTo}`, {
        method: "GET",
        //credentials: "include",
        headers: { ...headers },
      }).then((res) => {
        if (res.ok) {
          return res.json();
        } else {
          return { message: 0, data: [] };
        }
      }),
  });
  useEffect(() => {
    if (taskQuery.isPending) return;

    const { message, data } = taskQuery.data;
    setRowData(data);
    setMessage(message);
  }, [taskQuery]);

  if (taskQuery.isPending) return "Loading...";
  const columnDefs: ColDef[] = [
    { field: "id", headerName: "ID", width: 100 },
    { field: "skuName", headerName: "商品名称", flex: 1 },
    { field: "skuId", headerName: "商品编号", flex: 1 },
    { field: "shopName", headerName: "店铺", flex: 1 },
    { field: "shopPrice", headerName: "店铺价格", flex: 1 },
    { field: "platformPrice", headerName: "平台价格", flex: 1 },
    { field: "detail", headerName: "详细信息", flex: 2 },
    { field: "source", headerName: "来源", flex: 1 },
    {
      field: "updateTime",
      headerName: "更新时间",
      flex: 1,
      valueGetter: (params) => {
        const { data } = params;
        const date = new Date(data.updateTime);
        return date.toLocaleDateString();
      },
    },
    { field: "taskId", headerName: "任务ID" },
  ];

  if (taskQuery.error) return "An error has occurred: ";
  return (
    <main className="flex flex-col grow">
      <div className="flex flex-col flex-grow">
        <div className="flex flex-row items-center">
          <DatePickerWithRange date={date} setDateAction={setDate} />
          <Button
            variant="link"
            onClick={() => {
              if (!date || !date.from || !date.to) {
                return;
              }
              setTimeFrom(date?.from?.toISOString());
              setTimeTo(date?.to?.toISOString());
            }}
          >
            查询
          </Button>
        </div>
        <Tabs defaultValue="charts" className="flex flex-grow">
          <TabsList className="grid w-full grid-cols-2">
            <TabsTrigger value="goods">数据</TabsTrigger>
            <TabsTrigger value="charts">图表</TabsTrigger>
          </TabsList>
          <TabsContent value="goods" className="flex flex-grow">
            <DataGrid columnDefs={columnDefs} rowData={rowData} />;
          </TabsContent>
          <TabsContent value="charts" className="flex flex-grow">
            <ChartsPage
              data={rowData}
              title={`from ${date?.from?.toLocaleString()} to ${date?.to?.toLocaleString()}`}
            />
          </TabsContent>
        </Tabs>
      </div>
    </main>
  );
};
export default GoodsPage;
